using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

using GRPCDemo.Network.Interfaces;

namespace GRPCDemo.Network.Sockets
{
    public class TcpSocketListener : SocketListenerBase, IDisposable
    {
        protected int connectionBacklog;
        protected IPEndPoint endPoint;

        protected Socket? listenerSocket;
        protected SocketAsyncEventArgs args;

        public bool IsRunning
        {
            get { return listenerSocket != null; }
        }


        #region Constructors


        public TcpSocketListener(string address, int port, int connectionBacklog)
            : this(IPAddress.Parse(address), port, connectionBacklog) { }

        public TcpSocketListener(IPAddress address, int port, int connectionBacklog)
            : this(new IPEndPoint(address, port), connectionBacklog) { }

        public TcpSocketListener(IPEndPoint endPoint, int connectionBacklog)
        {
            this.endPoint = endPoint;
            this.connectionBacklog = connectionBacklog;

            args = new SocketAsyncEventArgs();
            args.Completed += OnSocketAccepted;
        }

        #endregion

        #region Override

        public override void Start()
        {
            lock (this)
            {
                if (!IsRunning)
                {
                    listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    listenerSocket.Bind(endPoint);
                    listenerSocket.Listen(connectionBacklog);

                    BeginAccept(args);
                }
                else
                    throw new InvalidOperationException("The Server is already running.");
            }
        }


        public override void Stop()
        {
            lock (this)
            {
                if (listenerSocket == null)
                    return;
                listenerSocket.Close();
                listenerSocket = null;
            }
        }

        #endregion

        private void BeginAccept(SocketAsyncEventArgs args)
        {
            args.AcceptSocket = null;
            listenerSocket?.AcceptAsync(args);
        }


        private void OnSocketAccepted(object? sender, SocketAsyncEventArgs e)
        {
            SocketError error = e.SocketError;
            if (e.SocketError == SocketError.OperationAborted)
                return; //Server was stopped

            if (e.SocketError == SocketError.Success)
            {
                Socket? handler = e.AcceptSocket;
                OnSocketConnected(handler);
            }

            lock (this)
            {
                BeginAccept(e);
            }
        }


        #region IDisposable Members

        private Boolean disposed = false;

        ~TcpSocketListener()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Stop();
                    if (args != null)
                        args.Dispose();
                }

                disposed = true;
            }
        }

        #endregion
    }
}
